package homework_4;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.Flags.Flag;
import javax.mail.Message.RecipientType;
import javax.mail.internet.*;

import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.imap.IMAPStore;






public class Email {
	private static final String sendHost = "smtp.sina.com";
	private static final String receiveHost = "imap.sina.com";
	private static final String home_address = "leejy2333@sina.com";
	private static final String password = "ljy123456789";
	
	
	public static Session getSendSession() {
		Properties props = System.getProperties();
		props.put("mail.smtp.host", sendHost);
		props.put("mail.smtp.auth", "true");
		Session session = Session.getDefaultInstance(props, new Authenticator() {
			@Override
			public PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(home_address, password);
			}
			
		});
		return session;
	}
	
	public static Session getReceiveSession() {
		Properties props = new Properties();
		
		props.put("mail.imap.host", receiveHost);
		props.put("mail.store.protocol", "imap");
		Session session = Session.getDefaultInstance(props, new Authenticator() {
			@Override
			public PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(home_address, password);
			}
			
		});
		return session;
	}
	
	public static void sendMail(Session session, InternetAddress[] addressGroup) {
		
		try {
			MimeMessage message = new MimeMessage(session);
			message.setFrom(new InternetAddress(home_address));
			message.setSubject("Java");
			addContentForMessage(message);
			message.addRecipients(RecipientType.TO, addressGroup);
			Transport.send(message);
		} catch (MessagingException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
 	}
	private static void addContentForMessage(MimeMessage msg) {
		try {
	        //用于组合文本和图片，"related"型的MimeMultipart对象
	        MimeMultipart contentMulti = new MimeMultipart("related");

	        //正文部分
	        String content = "Do you like me?";
	        MimeBodyPart textBody = new MimeBodyPart();
	        textBody.setContent(content,"text/html;charset=utf-8");

	        contentMulti.addBodyPart(textBody);

	        //图片部分
	        MimeBodyPart jpgBody = new MimeBodyPart();
	        FileDataSource jpgDS = new FileDataSource("picture.jpg");
	        jpgBody.setDataHandler(new DataHandler(jpgDS));
	        jpgBody.setHeader("Content-ID","<picture>");

	        contentMulti.addBodyPart(jpgBody);;
			msg.setContent(contentMulti);
		} catch (MessagingException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
	}
	//接受邮件并进行分析
	public static void receiveMail(Session session) {
		IMAPStore store = null;
		IMAPFolder folder = null;

		StringBuffer content = new StringBuffer(30);  
		try {
			store = (IMAPStore)session.getStore("imap");
			store.connect(home_address, password);
			folder = (IMAPFolder)store.getFolder("INBOX");
			folder.open(Folder.READ_WRITE);
			
			Message[] messages = folder.getMessages();
			for (Message message : messages) {
				// 只查看未读文件
				if (!message.getFlags().contains(Flag.SEEN)) {
					getMailTextContent(message, content); 
					judgeAnwser(content.toString(), message.getFrom()[0].toString());
					//设置邮件已读
					message.setFlag(Flag.SEEN, true);
				}
			}
            
		} catch (NoSuchProviderException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
		
			try {
				if (folder != null) {
	                folder.close(true);
	            }
	            if (store != null) {
	                store.close();
	            }
			} catch (Exception e) {
	            e.printStackTrace();
	        }
		}
		
	}
	
	private static void getMailTextContent(Part part, StringBuffer content) throws MessagingException, IOException {  
		//如果是文本类型的附件，通过getContent方法可以取到文本内容，但这不是我们需要的结果，所以在这里要做判断  
	    boolean isContainTextAttach = part.getContentType().indexOf("name") > 0;   
	    if (part.isMimeType("text/*") && !isContainTextAttach) {  
	        content.append(part.getContent().toString()); 
	    } else if (part.isMimeType("message/rfc822")) {   
	        getMailTextContent((Part)part.getContent(),content);  
	    } else if (part.isMimeType("multipart/*")) {  
	        Multipart multipart = (Multipart) part.getContent();  
	        BodyPart bodyPart = multipart.getBodyPart(0);  
	        getMailTextContent(bodyPart,content);
	    }  
	}  
	
	private static void judgeAnwser(String anwser, String from) {
		String string = from + "回复: ";
		if (anwser.toLowerCase().contains("yes")) {
			System.out.println(string + "Yes");
		} else {
			System.out.println(string + "No");
		}
		
	}
	
	public static void main(String[] args) {
		
		DBHelper dbHelper = new DBHelper("select * from new_table");
		Session sendSession = getSendSession();
		try {
			
			ResultSet result = dbHelper.pst.executeQuery();
			ArrayList<String> addresses = new ArrayList<>();
			while(result.next()) {
				String address = result.getString(1);
				addresses.add(address);
			}
			InternetAddress[] addressGroup = new InternetAddress[addresses.size()];
			int i = 0;
		
			for (String str : addresses) {
				addressGroup[i] = new InternetAddress(str);
				i++;
			}
			Email.sendMail(sendSession, addressGroup);
			
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (AddressException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			dbHelper.close();
		}
		
		// 新建线程检测邮箱，每4秒检测一次，只有当邮件未读时对其进行分析
		new Thread() {
    		public void run() {
    			while(true) {
    				
    				Session receiveSession = getReceiveSession();
    				receiveMail(receiveSession);
    				try {
    					// 每隔4秒检查一次邮件
						Thread.sleep(4000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
    			}
    		}
    	}.start();
	}
}
